<?php
cmspad_import('widget.Widget');
class ListWidget extends Widget{

	private $size;
	
	private $multiple;
	
	private $options = array();
	
	public function addOption($title, $value){
		$this->options[$value] = $title;
	}
	
	public function delOption($value){
		unset($this->options[$value]);
	}
	
	public function query($table, $title, $value, $condition = null){
		$this->options = array();
		$db = cmspad_database();
		$sql = 'SELECT `'.$title.'`,`'.$value.'` FROM `'.$table.'`'.($condition?' WHERE '.$condition:'');
		$rs = $db->query($sql);
		foreach($rs as $r){
			$this->addOption($r[$title], $r[$value]);
		}
	}
	
	public function __toString(){
		$html = '<SELECT';
		if($this->id){
			$html .= ' id="'.$this->id.'"';
		}
		if($this->name){
			$html .= ' name="'.$this->name.'"';
		}
		if($this->class){
			$html .= ' class="'.$this->class.'"';
		}
		if($this->style){
			$html .= ' style="'.$this->style.'"';
		}
		if($this->size){
			$html .= ' size="'.$this->size.'"';
		}else{
			$html .= ' size="1"';
		}
		if($this->multiple){
			$html .= ' multiple="multiple"';
		}
		$html .= '>';
		foreach($this->options as $v => $t){
			$html .= '<OPTION value="'.$v.'"';
			if($this->value){
				if($this->multiple && is_array($this->value)){
					if(in_array($v, $this->value)){
						$html .= ' selected="selected"';
					}
				}else{
					if($v == $this->value){
						$html .= ' selected="selected"';
					}
				}
			}
			$html .= '>'.$t.'</OPTION>';
		}
		$html .= '</SELECT>';
		return $html;
	}
}
?>